// 导入控制类
const {Controller}  = require('egg');
// 文件存储
const fs = require('fs');
const path = require('path');
const pump= require('mz-modules/pump');

// 创建上传控件
class Upload extends Controller{
    async upload(){
      try{
        let parts = this.ctx.multipart({ autoFields: true });
        let stream, img_list = []; // 图片访问地址集合
        while ((stream = await parts()) != null) {
          if (!stream.filename) {
            break;
          }
          // 文件名为：时间戳+随机字符串+.文件后缀
          let filename = (new Date()).getTime() + Math.random().toString(36).substr(2) + path.extname(stream.filename).toLocaleLowerCase();
          // 上传图片的目录
          let target = 'app/public/upload/' + filename;
          img_list.push('/public/upload/' + filename);
          //   创建文件写入流
          let writeStream = fs.createWriteStream(target);
          await pump(stream, writeStream);
        }
        // 如果用户原先有头像,先将原有图片在服务器中删除,如果没有则不执行
        if(this.ctx.query.url !== 'null'){
          await this.ctx.service.deleteFile.delete(this.ctx.query.url)
        }
        // 将用户上传的图片路径保存到数据库中
         const res = await this.ctx.service.user.modifyUserInfo(this.ctx.params.id,{avatar:`http://127.0.0.1:7001${img_list[0]}`})
        if(res){
            this.ctx.body = {
                code:200,
                msg:'图片上传成功',
                url: img_list,
                fields: parts.field
              }
        }else{
            this.ctx.body = {
                code:500,
                msg:'图片上传失败'
            }
        }
      }catch(e){
        console.log(e);
        this.ctx.body = {
          code:500,
          msg:'服务器错误'
      }
      }
      }
   
    
}

// 导出
module.exports = Upload;